<?php

namespace App\Models\Common;

use App\Models\BaseModel;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;

class Attachment extends BaseModel
{

    protected $table = 'attachments';
    protected $fillable = ['original_name', 'store_name', 'extension', 'size', 'mime_type', 'type', 'from_table', 'from_id', 'from_field', 'data_scope'];

    public function addAttachment($data)
    {
        $result = [];

        if (Auth::check()) {
            $dataScope = $this->getDataScope();
        } else {
            $dataScope = null;
        }

        foreach ($data as $value) {
            $value['data_scope'] = $dataScope;
            $result[] = $this->create($value);
        }

        return $result;
    }

    public function deleteAttachment($data, $fileDir = 'uploads')
    {
        $model = $this->where('store_name', $data['store_name'])->first();

        if (!$model) {
            return null;
        }

        if ($model->delete()) {
            Storage::delete($fileDir . '/' . $data['store_name'] . '.' . $model->extension);

            return $model->id;
        }

        return false;
    }

    public function getAttachmentList($ids)
    {
        $idsArr = json_decode($ids);

        if (is_array($idsArr)) {
            return $this->whereIn('id', $idsArr)->get(['id', 'from_id', 'from_field', 'original_name', 'store_name'])->toArray();
        }

        return null;
    }

    public function isExist($filename)
    {
        $model = $this->where('store_name', $filename)->first();

        if (!$model) {
            return null;
        }

        return $model;
    }

}
